package com.icss.flow.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.icss.flow.pojo.dto.Filter;
import com.icss.flow.pojo.dto.TLayoutConfigDTO;
import com.icss.flow.pojo.entity.TLayoutConfig;
import com.icss.flow.pojo.entity.TMetaField;
import com.icss.flow.pojo.vo.*;
import com.icss.flow.service.TLayoutConfigService;
import com.icss.flow.mapper.TLayoutConfigMapper;
import com.icss.flow.service.TMetaFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【t_layout_config】的数据库操作Service实现
 * @createDate 2024-04-10 14:38:25
 */
@Service
public class TLayoutConfigServiceImpl extends ServiceImpl<TLayoutConfigMapper, TLayoutConfig>
        implements TLayoutConfigService {

    public final String APPLY_TYPE_DEFAULT_FILTER = "DEFAULT_FILTER";
    public final String SHARE_TO_ALL = "ALL";
    public final String SHARE_TO_SELF = "SELF";

    public final String APPLY_TYPE_LIST = "LIST";
    public final String APPLY_TYPE_SEARCH = "SEARCH";

    @Autowired
    public TMetaFieldService tmetaFieldService;

    public List<TLayoutConfig> getListByEntityCode(Integer entityCode) {
        LambdaQueryWrapper<TLayoutConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TLayoutConfig::getEntityCode, entityCode);
        return this.list(lqw);
    }

    @Override
    public Boolean saveConfig(TLayoutConfigDTO tLayoutConfigDTO) {
        LambdaQueryWrapper<TLayoutConfig> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TLayoutConfig::getEntityCode, tLayoutConfigDTO.getEntityCode());
        lqw.eq(TLayoutConfig::getShareTo, tLayoutConfigDTO.getShareTo());
        TLayoutConfig layoutConfig = this.getOne(lqw);
        //判断当前是否有字段显示配置
        if (ObjectUtil.isEmpty(layoutConfig)) {
            //新增配置
            TLayoutConfig saveLayoutConfig = new TLayoutConfig();
            saveLayoutConfig.setLayoutConfigId("0000015-" + UUID.randomUUID().toString().replace("-", ""));
            saveLayoutConfig.setEntityCode(tLayoutConfigDTO.getEntityCode());
            saveLayoutConfig.setConfig(tLayoutConfigDTO.getConfig());
            saveLayoutConfig.setApplyType(tLayoutConfigDTO.getApplyType());
            saveLayoutConfig.setShareTo(tLayoutConfigDTO.getShareTo());
            return this.save(saveLayoutConfig);
        }
        layoutConfig.setConfig(tLayoutConfigDTO.getConfig());
        return this.updateById(layoutConfig);
    }

    /**
     * 获取默认查询配置、快速搜索字段配置、自定义列显示配置、默认列显示配置
     * @param entityCode
     * @return
     */
    @Override
    public LayoutListVO getLayoutList(Integer entityCode) {
        LayoutListVO layoutListVO = new LayoutListVO();
        List<TLayoutConfig> layoutConfigs = this.getListByEntityCode(entityCode);
        Map<String, LayoutConfigListVO> listApplyTypeMaps = new HashMap<>();

        if (CollectionUtil.isNotEmpty(layoutConfigs)) {
            //搜索字段
            Optional<TLayoutConfig> optional = layoutConfigs.stream().filter(layoutConfig -> layoutConfig.getApplyType().equals(APPLY_TYPE_SEARCH)).findFirst();
            if (optional.isPresent()) {
                TLayoutConfig searchLayoutConfig = optional.get();
                LayoutConfigListVO searchConfigLayoutConfigListVO = BeanUtil.copyProperties(searchLayoutConfig,LayoutConfigListVO.class);
                layoutListVO.setSearch(searchConfigLayoutConfigListVO);
            }
            Optional<TLayoutConfig> filterOptional = layoutConfigs.stream().filter(layoutConfig -> layoutConfig.getApplyType().equals(APPLY_TYPE_DEFAULT_FILTER)).findFirst();
            if(filterOptional.isPresent()) {
                //默认查询
                TLayoutConfig defaultLayoutConfig = filterOptional.get();
                LayoutConfigListVO defaultConfigLayoutConfigListVO = BeanUtil.copyProperties(defaultLayoutConfig,LayoutConfigListVO.class);
                layoutListVO.setDefaultFilter(defaultConfigLayoutConfigListVO);
            }

            //获取当前已有的列显示配置 (自定义列显示/默认列显示) applyType=List
            listApplyTypeMaps = layoutConfigs.stream().filter(layoutConfig -> layoutConfig.getApplyType().equals(APPLY_TYPE_LIST))
                    .map(layoutConfig -> BeanUtil.copyProperties(layoutConfig,LayoutConfigListVO.class))
                    .collect(Collectors.toMap(LayoutConfigListVO::getShareTo, layoutConfigListVO -> layoutConfigListVO));

        }
        //无配置
        LayoutConfigListVO configListVO;
        if (ObjectUtil.isEmpty(listApplyTypeMaps.get(SHARE_TO_ALL))) {
            configListVO = getLayoutConfigListVO(entityCode, SHARE_TO_ALL);
            listApplyTypeMaps.put(SHARE_TO_ALL, configListVO);
        }
        if (ObjectUtil.isEmpty(listApplyTypeMaps.get(SHARE_TO_SELF))) {
            configListVO = getLayoutConfigListVO(entityCode, SHARE_TO_SELF);
            listApplyTypeMaps.put(SHARE_TO_SELF, configListVO);
        }
        layoutListVO.setList(listApplyTypeMaps);
        return layoutListVO;
    }

    /**
     * 根据实体编码entityCode和应用类型applyType以及指向类型shareTo获取布局配置
     *
     * @param entityCode
     * @param applyType
     * @param shareTo
     * @return
     */
    @Override
    public TLayoutConfig getConfigByCodeAndApplyTypeAndShareTo(Integer entityCode, String applyType, String shareTo) {
        LambdaQueryWrapper<TLayoutConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TLayoutConfig::getEntityCode, entityCode);
        queryWrapper.eq(StrUtil.isNotEmpty(applyType), TLayoutConfig::getApplyType, applyType);
        queryWrapper.eq(StrUtil.isNotEmpty(shareTo), TLayoutConfig::getShareTo, shareTo);
        return this.getOne(queryWrapper);
    }

    private LayoutConfigListVO getLayoutConfigListVO(Integer entityCode, String shareTo) {
        LayoutConfigListVO configListVO = new LayoutConfigListVO();
        configListVO.setApplyType(APPLY_TYPE_LIST);
        configListVO.setEntityCode(entityCode);
        configListVO.setShareTo(shareTo);
        List<FieldConfigVO> fieldConfigVOList = new ArrayList<>();
        //获取手动新增的字段作为默认查询字段
        LambdaQueryWrapper<TMetaField> fieldlqw = new LambdaQueryWrapper<>();
        fieldlqw.eq(TMetaField::getEntityCode, entityCode);
        fieldlqw.eq(TMetaField::getDefaultMemberOfListFlag, 1);
        List<TMetaField> tMetaFields = tmetaFieldService.list(fieldlqw);
        tMetaFields.forEach(item -> {
            FieldConfigVO fieldConfigVO = new FieldConfigVO() {{
                setIsNameField(item.getNameFieldFlag() == 1);
                setIsNullable(item.getNullable() == 1);
                setIsCreatable(item.getCreatable() == 1);
                setIsUpdatable(item.getUpdatable() == 1);
                setFieldType(item.getType());
                setFieldName(item.getPhysicalName());
                setFieldLabel(item.getLabel());
            }};
            fieldConfigVOList.add(fieldConfigVO);
        });
        configListVO.setConfig(JSONUtil.toJsonStr(fieldConfigVOList));
        return configListVO;
    }


}




